//
//  SKComposeViewController.swift
//  WeiboProjectYL
//
//  Created by yanli on 16/7/18.
//  Copyright © 2016年 mountainPassCell. All rights reserved.
//

import UIKit
import SVProgressHUD

//  发微博控制器
class SKComposeViewController: UIViewController {

    // MARK: -- 懒加载控件
    private lazy var titleLabel: UILabel = {
        
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
        
        
        // 判断用户名是否为空(获取用户名)
        if let name = SKUserAccountViewModel.shareUserAccount.userAccount?.name {
            
            let title = "发微博\n\(name)"
            
            // 不为空设置副文本
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            
            attributedStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            
            label.attributedText = attributedStr
            
        } else {
            label.text = "发微博"
        }
        
        // 多行显示
        label.numberOfLines = 0
        label.textAlignment = .Center
        
        label.sizeToFit()
        return label
    }()
    
    
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        // 添加事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        // 设置 背景图片及文字
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        button.setTitle("发送", forState: .Normal)
        //  设置字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.size = CGSize(width: 45, height: 30)
        
        //  再次设置没有用
        // button.enabled = false

        return button
    }()
    
    
    // 自定义 textview
    private lazy var textView: SKComposeTextView = {
        let view = SKComposeTextView()
        // 遵守代理 ,监听 textview 变换 打开 发送交互
        view.delegate = self
        //
        view.placeHolder = "听说下雨天音乐跟辣条更配哟~"
        view.font = UIFont.systemFontOfSize(15)
        //view.textColor = UIColor.grayColor()
        
        //  垂直方向开启弹簧效果
        view.alwaysBounceVertical = true
        
        return view
    }()
    
    // toolbar
    private lazy var toolBar: SKComposeToolBar = {
        let view = SKComposeToolBar(frame: CGRectZero)
        return view
    }()
    
    //  配图
    private lazy var pictureView: SKComposePictureView = {
        let view = SKComposePictureView()
        return view
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.whiteColor()
        setupUI()
    }

    
    private func setupUI() {
        
        //  监听键盘改变  (监听系统发出的通知)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 设置 navigationItem
        setupNavUI()
        
        // 添加到视图
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        // 添加约束  布局
        // 发微博文字 textView
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            //设置 textView 底部是 toolBar 顶部
            make.bottom.equalTo(self.toolBar.snp_top)
        }
        
        // 下面 toolBar
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(40)
        }
        // 发微博配图
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }

        
        //  设置闭包 (在 toolBar 中设置的闭包)
        toolBar.selectedToolBarButtonClosure = { [weak self] (type: SKComposeToolBarButtonType) in
            
            switch type {
            case .Picture:
                print("图片")
                // 调用点击 图片相关的操作
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
            case .Add:
                print("加号")
            }
            
            
        }
        
        //  发微博页面的配图 定义的闭包
        pictureView.didSelectedAddClosure = { [weak self] in
            //  打开图片选择器
            self?.didSelectedPicture()
        }
        
        
    }
    
    
    // 设置 navigationItem
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //  根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    
    
    // MARK:    --  监听键盘frame改变的事件
    @objc private func keyboardChangeFrame(noti: NSNotification) {
        // 查看系统发送通知内容,获取关键字,取值
        //print(noti)
        
        //  获取屏幕的frame  这个地方注意类型转换
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //  获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //  更新 toolBar 底部 约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        
        //  执行动画(重新布局) duration 取的是系统键盘弹出所用的时间
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    // MARK: -- 点击事件处理
    @objc private func cancelAction() {
        // 先收取键盘
        self.view.endEditing(true)
        // 再dismiss
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //  发送微博
    @objc private func sendAction() {
        
        //  带图片微博上传接口
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            let accessToken = SKUserAccountViewModel.shareUserAccount.accessToken!
            let text = textView.text!
            SVProgressHUD.show()
            SKNetworkTools.shareTools.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }else {
                    //  发送成功
                    SVProgressHUD.showSuccessWithStatus("发送成功")
                }
            })
        } else {
            //  发送文字微博接口
            let accessToken = SKUserAccountViewModel.shareUserAccount.accessToken!
            let text = textView.text!
            SVProgressHUD.show()
            SKNetworkTools.shareTools.update(accessToken, status: text) { (response, error) -> () in
                if error != nil {
                    print(error)
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    return
                }
                
                
                //  发送成功
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }
        }
    }
    
    
    //  移除通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    


}




// MARK: -- toolbar按钮点击的相关操作 UIImagePickerController 遵守两个协议
extension SKComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    // 图片相关操作
    func didSelectedPicture() {
        let imagePictureCtr = UIImagePickerController()
        //  设置代理
        imagePictureCtr.delegate = self
        //  判断是否支持这个来源类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            imagePictureCtr.sourceType = .Camera
            print("支持相机")
        } else {
            imagePictureCtr.sourceType = .PhotoLibrary
            print("不支持相机,使用的图库")
        }
        
        //  判断是否支持前置或者后者摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("支持后置摄像头")
        } else {
            print("前后置摄像头不支持")
        }
        
        //  允许用户编辑
        //imagePictureCtr.allowsEditing = true
        
        // 跳转控制器  UIImagePickerController
        presentViewController(imagePictureCtr, animated: true, completion: nil)
        
    }
    
    
    //  获取选中的图片 , 如果实现了协议就不会自己调用dismissViewControllerAnimated
    // 在图库里面 选择完图片后
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 压缩选择 的图片 控制内存
        let scaleImage = scaleImageWithScaleWidth(200, image: image)
       // print(scaleImage)
        
        // 添加压缩后的图片
        pictureView.addImage(scaleImage)
        
        
        //  手动自己 dismiss 销毁图库 控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 进图相册后的 右上角 取消按钮
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        // 如果自己写了这个方法, 手动自己 dismiss
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
    /**
     根据指定压缩后的宽度,压缩图片  解决app 内存问题
     
     - parameter width: 压缩的宽度
     - parameter image: 需要压缩的图片
     
     - returns:   压缩后的图片
     */
    private func scaleImageWithScaleWidth(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        
        //  根据压缩后的宽度计算压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        
        //  压缩后的大小
        let size = CGSize(width: scaleWidth, height: scaleHeight)
        //  开启上下文
        UIGraphicsBeginImageContext(size)
        
        //  把图片渲染到指定范围内
        image.drawInRect(CGRect(origin: CGPointZero, size: size))
        //  获取上下文中压缩后的图片
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //  关闭上下文
        UIGraphicsEndImageContext()
        
        // 返回压缩后的图片
        return scaleImage
        
    }
    
    
    
    
}


// UITextViewDelegate 代理方法
extension SKComposeViewController: UITextViewDelegate {
    
    // 监听 textView 是否输入, 发生改变
    func textViewDidChange(textView: UITextView) {
        //  根据文本内容判断发送按钮是否可用 hasText() 有无内容
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    // 因为 TextView 继承 scrollView 所以可以使用 监听滚动
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        // 结束编辑,收回键盘
        self.view.endEditing(true)
    }
    
}
